package com.security.springsecuritylearn02.config;

import com.security.springsecuritylearn02.entity.Login;
import com.security.springsecuritylearn02.entity.MyUserDetails;
import com.security.springsecuritylearn02.mappers.HelloMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author llj
 * @create 2022-06-28 20:23
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private HelloMapper helloMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Login byUsername = helloMapper.getByUsername(username);
        MyUserDetails myUserDetail=new MyUserDetails();
        if(StringUtils.isEmpty(username)){
            throw new RuntimeException("用户名不能为空！");
        }
        if(byUsername==null){
            throw new RuntimeException("用户名不存在！");
        }
        //创建权限集合，并且把数据库权限加到集合中，然后注入容器中
        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
        String roles = byUsername.getRoles();
        if(roles!=null){
            authorities.add(new SimpleGrantedAuthority(roles.trim()));
        }
        //这个user是springsecurity的类，主要是用来保存用户名，用户权限，用户密码
        return new User(byUsername.getUsername(),byUsername.getPassword(),authorities);
    }
}
